# -*- coding: utf-8 -*-
"""
@ Created on 2024-06-14 12:23
---------
@summary: 用户API路由
---------
@author: Lsaiah
"""

from fastapi import APIRouter, Depends, Query
from typing import Optional
from datetime import datetime
from core.auth import AuthHandler
from core.response import ResponseModel, ListResponseModel
from ..models.form import UserCreateRequest, UserUpdateRequest
from ..models.curd import UserCRUD
from constant import *
from log import logger

user_router = APIRouter(prefix="/system/user", tags=["系统用户管理"])
auth_handler = AuthHandler()


@user_router.get("/page", response_model=ListResponseModel)
async def get_users(
    page: int = Query(1, ge=1, description="页码"),
    size: int = Query(10, ge=1, le=100, description="每页数量"),
    search: Optional[str] = Query(None, description="搜索关键词"),
    is_active: Optional[bool] = Query(None, description="是否激活"),
    current_user = Depends(auth_handler.get_current_active_user())
):
    """获取用户列表"""
    try:
        skip = (page - 1) * size
        # 获取用户列表
        users = await UserCRUD.get_list(skip=skip, limit=size, search=search, is_active=is_active)
        # 统计总数
        total = await UserCRUD.count_list(search=search, is_active=is_active)
        # 构建响应数据
        user_list = []
        for user in users:
            user_data = {
                "id": user.id,
                "username": user.username,
                "email": user.email,
                "dept_id": user.dept_id,
                "phone": user.phone,
                "full_name": user.full_name,
                "is_active": user.is_active,
                "is_superuser": user.is_superuser,
                "last_login": user.last_login.isoformat() if user.last_login else None,
                "created_at": user.created_at.isoformat(),
                "updated_at": user.updated_at.isoformat()
            }
            user_list.append(user_data)
        
        return ListResponseModel.success(
            list_data=user_list,
            page=page,
            size=size,
            total=total
        )
        
    except Exception as e:
        logger.error(f"获取用户列表失败: {str(e)}")
        return ListResponseModel(
            code=CODE_ERROR,
            message="获取用户列表失败",
            data=None,
            timestamp=datetime.now().isoformat()
        )


@user_router.get("/get", response_model=ResponseModel)
async def get_user(
    id: int = Query(..., description="用户ID"),
    current_user = Depends(auth_handler.get_current_active_user())
):
    """获取用户详情"""
    try:
        user = await UserCRUD.get_user_by_id(id)
        if not user:
            return ResponseModel.not_found("用户不存在")
        
        user_data = {
            "id": user.id,
            "username": user.username,
            "email": user.email,
            "dept_id": user.dept_id,
            "phone": user.phone,
            "full_name": user.full_name,
            "is_active": user.is_active,
            "is_superuser": user.is_superuser,
            "last_login": user.last_login.isoformat() if user.last_login else None,
            "created_at": user.created_at.isoformat(),
            "updated_at": user.updated_at.isoformat()
        }
        
        return ResponseModel.success(data=user_data)
        
    except Exception as e:
        logger.error(f"获取用户详情失败: {str(e)}")
        return ResponseModel.error(
            message="获取用户详情失败",
            code=CODE_ERROR
        )


@user_router.post("/create", response_model=ResponseModel)
async def create_user(
    user_data: UserCreateRequest,
    current_user = Depends(auth_handler.get_current_superuser())
):
    """创建用户"""
    try:
        # 检查用户名是否已存在
        existing_user = await UserCRUD.get_user_by_username(user_data.username)
        if existing_user:
            return ResponseModel.error(
                message=MESSAGE_USER_ALREADY_EXISTS,
                code=CODE_USER_ALREADY_EXISTS
            )
        
        # 检查邮箱是否已存在
        if user_data.email:
            existing_email = await UserCRUD.get_user_by_email(user_data.email)
            if existing_email:
                return ResponseModel.error(
                    message="邮箱已存在",
                    code=CODE_USER_ALREADY_EXISTS
                )
        
        # 加密密码
        hashed_password = auth_handler.get_password_hash(user_data.password)
        
        # 创建用户数据
        create_data = {
            "username": user_data.username,
            "hashed_password": hashed_password,
            "email": user_data.email,
            "dept_id": user_data.dept_id,
            "phone": user_data.phone,
            "full_name": user_data.full_name,
            "is_active": user_data.is_active,
            "is_superuser": user_data.is_superuser
        }
        
        # 创建用户
        user = await UserCRUD.create(create_data)
        
        return ResponseModel.success(
            data={"user_id": user.id, "username": user.username},
            message=MESSAGE_DATA_CREATE_SUCCESS,
            code=CODE_DATA_CREATE_SUCCESS
        )
        
    except Exception as e:
        logger.error(f"创建用户失败: {str(e)}")
        return ResponseModel.error(
            message="创建用户失败",
            code=CODE_ERROR
        )


@user_router.put("/update", response_model=ResponseModel)
async def update_user(
    user_data: UserUpdateRequest,
    current_user = Depends(auth_handler.get_current_active_user())
):
    """更新用户"""
    try:
        # 检查用户是否存在
        user = await UserCRUD.get_user_by_id(user_data.id)
        if not user:
            return ResponseModel.not_found("用户不存在")
        
        # 构建更新数据
        update_data = {}
        if user_data.email is not None:
            update_data["email"] = user_data.email
        if user_data.full_name is not None:
            update_data["full_name"] = user_data.full_name
        if user_data.is_active is not None:
            update_data["is_active"] = user_data.is_active
        if user_data.is_superuser is not None:
            update_data["is_superuser"] = user_data.is_superuser
        if user_data.dept_id is not None:
            update_data["dept_id"] = user_data.dept_id
        if user_data.phone is not None:
            update_data["phone"] = user_data.phone
        if user_data.username is not None:
            update_data["username"] = user_data.username

            
        # 更新用户
        updated_user = await UserCRUD.update(user_data.id, update_data)
        if not updated_user:
            return ResponseModel.error(
                message="更新用户失败",
                code=CODE_ERROR
            )
        
        return ResponseModel.success(
            data={"user_id": updated_user.id, "username": updated_user.username},
            message=MESSAGE_DATA_UPDATE_SUCCESS,
            code=CODE_DATA_UPDATE_SUCCESS
        )
        
    except Exception as e:
        logger.error(f"更新用户失败: {str(e)}")
        return ResponseModel.error(
            message="更新用户失败",
            code=CODE_ERROR
        )


@user_router.delete("/delete", response_model=ResponseModel)
async def delete_user(
    id: int = Query(..., description="用户ID"),
    current_user = Depends(auth_handler.get_current_superuser())
):
    """删除用户"""
    try:
        if id == 0:
            return ResponseModel.error(
                message="不能删除超级管理员",
                code=CODE_ERROR
            )
        
        if id == current_user.id:
            return ResponseModel.error(
                message="不能删除自己",
                code=CODE_ERROR
            )
        
        # 检查用户是否存在
        user = await UserCRUD.get_user_by_id(id)
        if not user:
            return ResponseModel.not_found("用户不存在")
        
        # 删除用户
        success = await UserCRUD.delete(id)
        if not success:
            return ResponseModel.error(
                message="删除用户失败",
                code=CODE_ERROR
            )
        
        return ResponseModel.success(
            message=MESSAGE_DATA_DELETE_SUCCESS,
            code=CODE_DATA_DELETE_SUCCESS
        )
        
    except Exception as e:
        logger.error(f"删除用户失败: {str(e)}")
        return ResponseModel.error(
            message="删除用户失败",
            code=CODE_ERROR
        )
